package com.siwei.mes.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片处理工具（压缩图片）
 *
 * @author chenmaolin
 * @create 2021-11-12 10:05
 */
@Slf4j
public class ImgUtil {
    /**
     * 压缩图片
     *
     * @param file   文件
     * @param qality 压缩程度 取值0~1
     * @return
     * @throws IOException
     */
    public static File compressPictureByQality(File file, float qality) throws IOException {
        BufferedImage src = null;
        FileOutputStream out = null;
        ImageWriter imgwriter;
        ImageWriteParam imgWriteParams;
        log.debug("开始设定压缩图片参数");
        /**指定写图片的方式为 jpg*/
        imgwriter = ImageIO.getImageWritersByFormatName("jpg").next();
        imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
        /**要使用压缩，必须指定压缩方式为MODE_EXPLICIT*/
        imgWriteParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        /**压缩程度 0~1范围*/
        imgWriteParams.setCompressionQuality(qality);
        imgWriteParams.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
        ColorModel colorModel = ImageIO.read(file).getColorModel();
        /**指定压缩时使用的色彩模式*/
        imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));
        log.debug("结束设定压缩图片参数");
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        } else {
            log.info("图片转换前大小:{},字节", file.length());
            src = ImageIO.read(file);
            out = new FileOutputStream(file);
            imgwriter.reset();
            /**必须先指定 out值，才能调用write方法, ImageOutputStream可以通过任何*/
            imgwriter.setOutput(ImageIO.createImageOutputStream(out));
            /**调用write方法，就可以向输入流写图片*/
            imgwriter.write(null, new IIOImage(src, null, null), imgWriteParams);
            out.flush();
            out.close();
            log.info("图片转换后大小:{},字节", file.length());
            return file;
        }
    }
}
